package kz.pompei.oneGwtStands.client.remote;

import kz.pompei.OneGwt.ifaces.util.ClientUtil;
import kz.pompei.OneGwt.ifaces.util.Getter;

import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class AsyncTimer {
  private static int nextValue = 1;
  public static int time1 = 1;
  public static int time2 = 1;
  
  public static <T> void execute(final AsyncCallback<T> callback, final Getter<T> getter) {
    int t1 = time1;
    int t2 = time2;
    {
      String s = ClientUtil.getUrlParam( "t1" );
      if (s != null && s.length() > 0) {
        t1 = Integer.parseInt( s );
      }
    }
    {
      String s = ClientUtil.getUrlParam( "t2" );
      if (s != null && s.length() > 0) {
        t2 = Integer.parseInt( s );
      }
    }
    int delayMillis = nextValue++ % 2 == 0 ? t1 :t2;
    executeMillis( delayMillis, callback, getter );
  }
  
  public static <T> void executeMillis(int delayMillis, final AsyncCallback<T> callback,
      final Getter<T> getter) {
    new Timer() {
      @Override
      public void run() {
        T data;
        try {
          data = getter.get();
        } catch (Throwable e) {
          callback.onFailure( e );
          return;
        }
        callback.onSuccess( data );
      }
    }.schedule( delayMillis );
  }
}
